function [output subjectinfo] = calculateTfcDataForICA (subjectinfo, cfg)
tStart = tic;
output = [];
% fnES = fieldnames(subjectinfo.EpochData);
% for i = 1:length(fnES)
%     currentEpochset = fnES{i};    
%     fnEL = fieldnames(subjectinfo.EpochData.(currentEpochset).TfcData);
%     listOfTfcDataFiles = cell(1,length(fnEL));
%     for j = 1:length(fnEL)
%         currentElectrode = fnEL{j};
%         listOfTfcDataFiles{j} = subjectinfo.EpochData.(currentEpochset).TfcData.(currentElectrode).Filename;
%     end
%     [oooo subjectinfo] = calculateTfcDataPerEpochset(output, subjectinfo, currentEpochset, listOfTfcDataFiles);
% end
currentEpochset = 'SphereUnambiguousResponse';
listOfTfcDataFiles = {'D:\ECoG\Data\Timefreq\CW P10 Sphere Unambiguous Response Timefreq data.mat'}; % P10
[oooo subjectinfo] = calculateTfcDataPerEpochset(output, subjectinfo, currentEpochset, listOfTfcDataFiles);
output.TimePassed = toc(tStart);
end

function [output subjectinfo] = calculateTfcDataPerEpochset(output, subjectinfo, currentEpochset, list)
freqbindescriptions = {'7-13Hz'}; %'4-7Hz', '7-13Hz', '13-30Hz', '30-70Hz', '70-130Hz'
frequencies = [7,13]; %4,7 ; 7,13 ; 13,30 ; 30,70 ; 70,130
[Y,I] = sort(list);
firstloop = true;
tStart = tic;
for i = I % load in ASCII order...
    disp(['Loading file ' num2str(find(I==i)) '/' num2str(length(I)) '...']);
    load(list{i});
    disp(['  --> ' data.channel ' of ' data.epochs.name]);
    if firstloop;
        tfc.subject = subjectinfo.Name;
        tfc.epochs = currentEpochset;
        tfc.times = data.times;
        tfc.freqbins = frequencies;
        tfc.freqbindescriptions = freqbindescriptions;
        firstloop = false;
    end
    disp('  --> Calculating...');
    tfc.data.(data.channel) = CreateChannelCollapsedDataByTrialMean(data,frequencies);
    disp(['  --> Elapsed time since starting with this epochset: ' num2str(toc(tStart)) 's.']);
end

disp('All channels have been processed.');
disp('  --> Saving...');
filename = [getpref('ECoG','Data') 'Timefreq\TfcForICA\' subjectinfo.PrimaryPrefix ' ' currentEpochset ' TfcForICA.mat'];
save(filename, '-v7.3', 'tfc');
% subjectinfo.EpochData.(currentEpochset).TfcDatafile = filename;
end

function [tfcollapsed] = CreateChannelCollapsedDataByTrialMean(data, frequencies)
dabs = abs(data.tf); %TODO waarom hier de absolute waarde nemen? Zou niet nodig moeten zijn?
dabsm = dabs ./ repmat( mean(dabs, 2), [1,size(dabs,2),1]); %Dit is geen normalisatie van variantie, maar alleen van gemiddelde. Overleg met Maartje.
% for i=1:length(frequencies)
    tfcollapsed.frequencyrange = frequencies(:);
    bin = dabsm(data.freqs>=frequencies(1) & data.freqs<=frequencies(2),:,:); % Gets 'freq in bin' x 'time' x 'trials'
    timesByTrials = squeeze(mean(bin,1)); %calculate average per time point per trial for each freq bin: 
    tfcollapsed = timesByTrials';
% end

end